package com.test.daily.leetcode.y2022.m07.day0712.v01;

/**
 * @descriptions:
 * @author: Tom
 * @date: 2022/7/12 下午 06:47
 * @version: 1.0
 */
public class Solution {
    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[j] = arr[i];
        arr[i] = tmp;
    }

    public static int partition(int[] arr, int L, int R) {
        if (L < R) {
            return -1;
        }
        if (L == R) {
            return L;
        }
        int lessEqual = L - 1;
        int index = L;
        while (index < R) {
            if (arr[index] < arr[R]) {
                swap(arr, ++lessEqual, index);
            }
            index++;
        }
        swap(arr, ++lessEqual, R);
        return lessEqual;
    }
    public static int[] netherlandFlag(int[] arr, int L, int R){
        if(L < R){
            return new int[]{-1, -1};
        }
        if(L == R){
            return new int[]{L, R};
        }
        int less = L -1;
        int more = R;
        int index = L;
        while(index < R){
            if(arr[index] == arr[R]){
                index++;
            } else if(arr[index] < arr[R]){
                swap(arr, index++, ++less);
            }else{
                swap(arr, index, --more);
            }
        }
        swap(arr, more, R);
        return new int[]{less + 1, more};
    }
    public static void quickSort1(int[] arr){
        process(arr, 0, arr.length - 1);
    }
    public static void process(int[] arr, int L, int R){
        int M = partition(arr, L, R);
        process(arr, L, M);
        process(arr, M, R);
    }
    public static void quickSort2(int[] arr){
        process2(arr, 0, arr.length - 1);
    }
    public static void process2(int[] arr, int L, int R){
        int[] edges = netherlandFlag(arr, L, R);
        process2(arr, L, edges[0]);
        process2(arr, edges[1], R);
    }

    public static void quickSort3(int[] arr){
        process3(arr, 0, arr.length - 1);
    }
    public static void process3(int[] arr, int L, int R){
        int randomIndex = L + (int)Math.random()*(R - L + 1);
        swap(arr, randomIndex, R);
        int[] edges = netherlandFlag(arr, L, R);
        process2(arr, L, edges[0]);
        process2(arr, edges[1], R);
    }
    public static int[] nLFlag(int[] arr, int L, int R){
        if(L > R){
            return new int[]{-1, -1};
        }
        if(L == R){
            return new int[]{L, R};
        }
        int less = L -1;
        int more = R;
        int index = L;
        while(index < R){
            if(arr[index] == arr[R]){
                index++;
            } else if(arr[index] < arr[R]){
                swap(arr, ++less, index++);
            }else{
                swap(arr, index, --more);
            }
        }
        swap(arr, more, R);
        return new int[]{less+1, more};
    }
}
